<script lang="ts" setup>
import {ref, useSlots, watch} from 'vue';
import {getCssValue} from '@/utils'

const props = defineProps({
    gap: {type: Number, default: 10},
    size: {type: String, default: 'default'},
    fields: {type: Array<any>, default: []},
    abreast: {type: Boolean, default: false},
})

const value = defineModel();
const dataFormRef = defineModel("formRef");
const collapse = defineModel("collapse");

const emits = defineEmits(['changeCollapse'])

const element = ref();
const style = ref();
const labelWidth = ref<number>(96);

let slots = useSlots() as any;
if (slots.hasOwnProperty('default')) {
    slots = slots?.default();
}

// 监听屏幕变化
const resize = (el: HTMLElement) => {
    element.value = el;
    let count;
    const totalWidth = el.clientWidth; // 总长度
    const inputWidth = parseInt(getCssValue('--el-form-inline-content-width', el)?.replace("px", "") || "220"); // 输入框宽度
    const fontSize = parseInt(getCssValue('--el-form-label-font-size', el)?.replace("px", "") || "14"); // 字体宽度
    let span, max = 0, collapsed;
    // 计算每个表单项的label宽度， 12是label的padding宽度
    if (props.fields.length) {
        span = Object.values(props.fields).reduce((count: number, item: any) => {
            if (item.span) {
                count += item.span;
            } else {
                count ++;
            }
            let len = item.label.split('').length;
            if (max < len) {
                max = len;
            }
            return count;
        }, 0);
    } else {
        if (typeof slots[0]?.type === 'symbol') {
            slots = slots[0].children.filter((item: any) => item.type?.name === 'ElFormItem')
        }
        span = Object.values(slots).reduce((count: number, item: any) => {
            let value;
            if (item.props.style && !!(value = item.props.style['grid-column'])) {
                count += parseInt(value.split('/')[0].replace(/[^\d.]/g, ""))
            } else {
                count ++;
            }
            let len = item.props.label?.split('').length ?? 0;
            if (max < len) {
                max = len;
            }
            return count;
        }, 0)
    }
    // 计算最长文本宽度
    labelWidth.value = max * fontSize + 12;
    // 计算每个表单项大概宽度
    let itemWidth = labelWidth.value + inputWidth + props.gap;

    if (props.abreast) {
        count = Math.max(span, Math.floor(totalWidth / itemWidth));
        collapse.value = undefined;
    } else {
        count = Math.floor(totalWidth / itemWidth);
        collapse.value = span > count? true:undefined;
    }

    // 样式
    style.value = {
        display: 'grid',
        gridTemplateColumns: `repeat(${count}, minmax(0, 1fr))`,
        gridGap: `${props.gap}px`
    };

    watch(() => collapse.value, (v) => {
        const el = element.value.children[0];
        emits('changeCollapse', el, v);
    })
};

defineExpose({
    $ref: dataFormRef,
    $el: element,
    collapse
})
</script>

<template>
    <el-form ref="dataFormRef" :inline="true" :model="value" :label-width="abreast? '':labelWidth" :size="size" class="kt-grid-form__search" v-resize="resize">
        <div :style="style">
            <template v-if="fields.length > 0" v-for="field in props.fields" :key="field.prop" >
                <el-form-item :label="field.label" :prop="field.prop" :style="{'grid-column': `span ${field.span ?? 1} / span ${field.span ?? 1}`}">
                    <template #label="{label}">
                        <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                            {{label}}
                        </span>
                    </template>
                    <slot :name="field.slot || field.prop"/>
                </el-form-item>
            </template>
            <template v-else>
                <slot></slot>
            </template>
        </div>
    </el-form>
</template>

<style lang="scss">
.kt-grid-form__search {
    padding: 5px;

    .el-form-item {
        margin-bottom: 0;
        margin-right: 0
    }
}
</style>